import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/local'

import Login from '@/views/Login'
import Details from '@/views/Details'
import Layout from '@/views/Layout'
import Home from '@/views/Home'
import Class from '@/views/Class'
import Car from '@/views/Car'
import My from '@/views/My'

Vue.use(VueRouter)

// 一级登录,layout
// 二级首页,分类,购物车,我的
const routes = [
  { path: '/login', component: Login },
  { path: '/details', component: Details },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'class', component: Class },
      { path: 'car', component: Car },
      { path: 'my', component: My }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置路由守卫
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
